import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Button, DatePicker, Badge, Select } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './DevTask.less';

const { Option } = Select;
const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
// const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['等待设置', '设置中', '设置成功', '设置失败', '设置超时'];
const statusMap = ['default', 'processing', 'success', 'error'];
const setType = [
  '设置亮度',
  '屏幕开关',
  '设置服务器地址',
  '设置心跳间隔',
  '设备重启',
  '设置WIFI/USB',
  '设备在线更新OTA',
  '查询设备硬件信息',
];

@connect(({ devtask, loading }) => ({
  devtask,
  loading: loading.models.devtask,
}))
@Form.create()
export default class DevTask extends PureComponent {
  state = {
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const { devName } = this.props.match.params;
    const { dispatch } = this.props;
    let payload = {};
    if (devName !== 'init') {
      payload = { devName };
    }
    dispatch({
      type: 'devtask/fetch',
      payload,
    });
  }

  getFromValue = () => {
    const { form } = this.props;
    let postvalue = {};
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const { entries } = Object;

      for (const [key, value] of entries(fieldsValue)) {
        if (value !== null && value !== undefined) {
          postvalue[key] = value;
        }
      }
      //console.log('postvalue', postvalue);
      if (postvalue.date && postvalue.date.length > 0) {
        const startTime = postvalue.date[0].format('YYYY-MM-DD HH:mm:ss');
        const endTime = postvalue.date[1].format('YYYY-MM-DD HH:mm:ss');
        postvalue = {
          ...postvalue,
          startTime,
          endTime,
        };
        delete postvalue.date;
      }
    });
    return postvalue;
  };
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    const postvalue = this.getFromValue();
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...postvalue,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'devtask/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'devtask/fetch',
      payload: {},
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch } = this.props;
    const postvalue = this.getFromValue();
    dispatch({
      type: 'devtask/fetch',
      payload: postvalue,
    });
  };

  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const { devName } = this.props.match.params;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={4} sm={24}>
            <FormItem>
              {getFieldDecorator('devId', {
                rules: [{ required: false, message: '请输入设备名称!' }],
                initialValue: devName === 'init' ? null : devName,
              })(<Input placeholder="设备ID" />)}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem>
              {getFieldDecorator('devName', {
                rules: [{ required: false, message: '请输入设备名称!' }],
                initialValue: devName === 'init' ? null : devName,
              })(<Input placeholder="设备名称" />)}
            </FormItem>
          </Col>
          <Col md={7} sm={24}>
            <FormItem>
              {getFieldDecorator('date')(
                <RangePicker
                  showTime={{ format: 'HH:mm' }}
                  format="YYYY-MM-DD HH:mm"
                  placeholder={['开始时间', '结束时间']}
                  // onChange={onChange}
                  // onOk={onOk}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>
          <Col md={3} sm={24}>
            <FormItem>
              {getFieldDecorator('setType')(
                <Select allowClear="true" placeholder="操作类型" style={{ width: '100%' }}>
                  {setType.map((item, index) => (
                    <Option value={index}>{item}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={3} sm={24}>
            <FormItem>
              {getFieldDecorator('setStatus')(
                <Select allowClear="true" placeholder="任务状态" style={{ width: '100%' }}>
                  {status.map((item, index) => (
                    <Option value={index}>{item}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={2} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    // //console.log('task', this.props.task);
    const { devtask, loading } = this.props;
    const { selectedRows } = this.state;
    const columns = [
      {
        title: '任务ID',
        dataIndex: 'setId',
      },
      {
        title: '设备ID',
        dataIndex: 'devId',
      },
      {
        title: '设备名称',
        dataIndex: 'devName',
      },
      {
        title: '任务状态',
        dataIndex: 'setStatus',
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]} />;
        },
      },

      {
        title: '操作类型',
        dataIndex: 'setType',
      },

      {
        title: '更新时间',
        dataIndex: 'updateTime',
        sorter: true,
      },
    ];

    return (
      <PageHeaderLayout title="任务查询">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <StandardTable
              rowKey="setId"
              selectedRows={selectedRows}
              loading={loading}
              data={devtask}
              columns={columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
